import ujson
import utime as time
import _thread
import app_network
import ntptime
import machine
import app_mqtt

global immed_report
immed_report = 0
def get_immed_report():
    global immed_report
    return immed_report

def set_immed_report(value):
    global immed_report
    immed_report = value

def get_server_state(cfg):
    if cfg["nettype"] == 0:        #4G-cat1+mqtt
        return app_mqtt.mqtt_get_server_state()
    if cfg["nettype"] == 2:     
        return 1
def set_server_state(cfg,value):
    if cfg["nettype"] == 0:        #4G-cat1+mqtt
        app_mqtt.mqtt_set_server_state(value)    

#获取utc时间
def get_localtime():   
    localtime = time.localtime()  #返回元组
    localtime2 = tuple(map(str,localtime[0:6]))
    timestr = "".join(list(localtime2))
    return timestr


def server_func(cfg):
    if cfg["netmode"] == 0:        #4G-cat1+mqtt
        ret = app_network.connect_4g()
    elif cfg["netmode"] == 1:        #以太网+mqtt
        ret = app_network.connect_eth()
    elif cfg["netmode"] == 2:        #局域网
        ret = app_network.connect_lan(cfg['lan']['ip'],cfg['lan']['subnet'],cfg['lan']['gateway'],cfg['lan']['dns'])
    elif cfg["netmode"] == 3:        #wifi
        ssid = cfg['wifi']['ssid']
        pwd =  cfg['wifi']['pwd']
        ret = app_network.connect_wifi(ssid,pwd)
    print('net',ret) 
    if ret:
        # 设置NTP服务器地址，默认可以使用"pool.ntp.org"
        ntp_server = "pool.ntp.org"
        for i in range(3):
            time.sleep(1)
            # 获取当前时间
            try:
                ntptime.settime()  # 使用默认的NTP服务器校时
            except OSError as e:
                print("NTP failed:", e)
            else:
                print("NTP校时成功")
        # 打印当前系统时间
        current_time = time.localtime()
        print("localtime:", current_time)  
        #连接mqtt平台 
        #app_mqtt.mqtt_connect()
        return True
    else:
        app_mqtt.mqtt_set_server_state(0)
        print('network failed')
        time.sleep(2)
        machine.reset()
        return False
        
def timing_update_data(cfg):
    if cfg["nettype"] == 0:        #4G-cat1+mqtt
        app_mqtt.mqtt_timing_update_data()

def ota_app_detec(cfg):
    if cfg["nettype"] == 0:       
        app_mqtt.mqtt_ota_app_detec()




